package com.free.freemarker.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;

public class Java {

	public static void main(String[] args) throws IOException {
//		Class<?> clazz = Q.class;
//		String path = System.getProperty("user.dir")+ "/src/test/java/com/test/Q.java";
//		Java j=new Java();
//		j.free(clazz, path);

	}
	
	
	public void free(Class<?>clazz,String path) throws IOException{
		File file = new File(path);
		FileInputStream fis = new FileInputStream(file);
		byte[] buf = new byte[fis.available()];
		fis.read(buf);
		fis.close();
		String str = new String(buf);
		StringBuilder sb = new StringBuilder(str);
		String simpleName = clazz.getSimpleName();

		int index = sb.indexOf(simpleName);
		sb.insert(index + simpleName.length(), " implements IVo<" + simpleName+ ">");

		StringBuilder sbAppend = new StringBuilder("@Override\n");
		sbAppend.append("public void get(String alias,"+simpleName+" t,Map<String,Object>map){\n");
		Field[] fArr = clazz.getDeclaredFields();
		Field f = null;
		String col=null;
		for (int i = 0, len = fArr.length; i < len; i++) {
			f = fArr[i];
			col=f.getName();
			
			sbAppend.append("t.set"+firstUpper(col)+"(("+f.getType().getName()+")map.get(alias+"+"\"_"+col+"\"));\n");
		}
		sbAppend.append("}\n\n");
		
		sbAppend.append("@Override\n");
		sbAppend.append("public List<IVo<"+simpleName+">> get(String alias,String col,Object condition, List<Map<String, Object>> mapList){\n ");
		sbAppend.append("List<IVo<"+simpleName+">>list=new ArrayList<IVo<"+simpleName+">>();\n");
		sbAppend.append(""+simpleName +" t=null;\n");
		sbAppend.append("Map<String,Object>map=null;\n");
		sbAppend.append("Object o=null;\n");
		sbAppend.append("for(int i=0,len=mapList.size();i<len;i++){\n");
		sbAppend.append("map=mapList.get(i);\n");
		sbAppend.append("o=map.get(alias+\"_\"+col);\n");
		sbAppend.append("if(condition==o){\n");
		sbAppend.append("t=new "+simpleName+"();\n");
		sbAppend.append("t.get(alias, t, map);\n");
		sbAppend.append("list.add(t);\n");
		sbAppend.append("}\n");
		sbAppend.append("}\n");
		sbAppend.append("return list;\n}\n");	
		index=sb.lastIndexOf("}");
		sb.insert(index, sbAppend);
		FileWriter fw = new FileWriter(path, false);
		PrintWriter pw = new PrintWriter(fw);
		pw.println(sb.toString());
		pw.close();
		fw.close();
	}
	/**
	 * 首字母大写
	 * @param property
	 * @return
	 */
	private  String firstUpper(String property){
		return property.substring(0,1).toUpperCase()+property.substring(1);
	}
	
	
}
